package wtws.manager.in;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Queue;

import wtws.manager.in.interf.MessageReader;
import wtws.message.interf.TdwrProdMessage;
import wtws.util.JobConfig;
import wtws.util.SFTPManager;

public class FtpMessageReader extends MessageReader {

	public FtpMessageReader() {

	}

	public FtpMessageReader(Queue<TdwrProdMessage> q, JobConfig jobConfig) {
		super(q, jobConfig);
	}

	@Override
	public void run() {
		while (true) {
			getFiles();
			try {
				Thread.sleep(jobConfig.getInFreq());
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}

	@Override
	public void getFiles() {

		getFtpFiles();
		File lrDir = new File(jobConfig.getMsgInDir());
		File[] lrFiles = lrDir.listFiles();
		for (File file : lrFiles) {
			try {
				if (file.getName().contains("ppn")) {
					q.offer(PrecipitationDecoder.processFile(file));
				} else if (file.getName().contains("dat")) {
					ArrayList<TdwrProdMessage> qList;
					qList = AlphaMbDecoder.processFile(file);
					for (TdwrProdMessage msg : qList) {
						q.offer(msg);
					}

				}
			} catch (Exception e) {
				e.printStackTrace();
			}
			file.delete();
		}
	}

	private void getFtpFiles() {
		SFTPManager fm = new SFTPManager(jobConfig.getFtpUrl(), jobConfig.getFtpUser(), jobConfig.getFtpPasswd());
		try {
			fm.ftpLogin();
			fm.changeDir(jobConfig.getFtpPath());
			List<String> files = fm.ls("*.dat");
			for (String file : files) {
				fm.downloadFile(jobConfig.getMsgInDir() + File.separator + file, file);
				System.out.println("[INFO] downloaded: " + file);
			}
			fm.changeDir(jobConfig.getFtpPrecipPath());
			files = fm.ls("*.dat");
			for (String file : files) {
				fm.downloadFile(jobConfig.getMsgInDir() + File.separator + file, file);
				System.out.println("[INFO] downloaded: " + file);
			}
			fm.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
